package com.jingzhi.huimiao;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jingzhi.huimiao.bean.WordExampInfo;
import com.jingzhi.huimiao.utils.DataStoreUtil;
import com.jingzhi.huimiao.utils.SQLdm;

public class Test4Activity extends Activity implements OnClickListener {

	private static final int WHAT = 0;
	private static final int LASTWHAT = 1;
	private RelativeLayout rl_end;
	private ImageView iv_live;
	private ImageView iv_playagain;
	private ImageView iv_playnext;
	private ImageView iv_starcount;
	private ImageView iv_playagain_die;
	private TextView tv_rightlv;
	private SQLiteDatabase db;
	private ArrayList<Long> tasklist;
	private int rightcount;
	// private Cursor rawQuery;
	private Long chapterid;
	private Cursor exampInfocur;

	private TextView tv_test4_exp;
	private TextView tv_test4_c1;
	private TextView tv_test4_c2;
	private TextView tv_test4_c3;
	private TextView tv_test4_c4;
	private TextView tv_test4_translation;
	private ImageView iv_test4_lastone;
	private ImageView iv_test4_save;
	private ProgressBar pb_test4;
	private RelativeLayout rl_test4;
	
	private int i;
	private List<WordExampInfo> wordexampinfos;

	private TextView tv_title;
	private LinearLayout iv_back_tomain;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case 0:

				if (i < wordexampinfos.size() - 1) {
					i++;

						studyWord(wordexampinfos);

					pb_test4.incrementProgressBy(1);
				} else {

					 Toast.makeText(Test4Activity.this, "已经最后一个了....",0).show();
//					startActivity(new Intent(Test4Activity.this,
//							TaskActivity.class));
//					finish();
					 rl_end.setVisibility(View.VISIBLE);
					 iv_back_tomain.setClickable(false);
						// // 打开数据库输出流
						// SQLdm s = new SQLdm();
						// db = s.openDatabase(Test4Activity.this);

						rightcount = 0;
						for (int i = 0; i < tasklist.size(); i++) {
							Cursor rawQuery = db.rawQuery(
									"select id from word where pid ='"
											+ tasklist.get(i) + "' and word_right=2;",
									null);
							Log.e("rightcount-----fs-", tasklist.get(i).toString());
							rightcount += rawQuery.getCount();
							Log.e("rightcount-----fsfdsfsdf-", rawQuery.getCount() + "");
							if (rawQuery != null) {
								rawQuery.close();
							}
						}
						Log.e("TAG", "tttte");

						// if(rawQuery !=null){
						// Log.e("TAG", "iiiiii");
						// rawQuery.close();
						// rawQuery = null;
						// }
						//

						// 求得正确率
						double accuracy = rightcount / 82.0;
						Log.e("------", accuracy + "");
						tv_rightlv.setText((int) (accuracy * 100) + "%");
						if (accuracy >= 0.4) {
							iv_starcount.setVisibility(View.VISIBLE);
							iv_starcount.setBackgroundResource(R.drawable.star_three);
						} else if (accuracy >= 0.3) {
							iv_starcount.setVisibility(View.VISIBLE);
							iv_starcount.setBackgroundResource(R.drawable.star_two);
						} else if (accuracy >= 0.2) {
							iv_starcount.setVisibility(View.VISIBLE);
							iv_starcount.setBackgroundResource(R.drawable.star_one);
						} else {
							iv_starcount.setVisibility(View.GONE);
							iv_live.setBackgroundResource(R.drawable.die);
							iv_playagain_die.setVisibility(View.VISIBLE);
							iv_playagain.setVisibility(View.GONE);
							iv_playnext.setVisibility(View.GONE);

						}
						// tv_rightlv.setText(accuracy*100+"%");

						if (db != null) {
							Log.e("TAG", "ddddd");
							db.close();
						}

						setOnListener();
				}

				break;
			case 1:

				if (i > 0) {
					i--;

						studyWord(wordexampinfos);
					
					pb_test4.incrementProgressBy(-1);
				} else {

					 Toast.makeText(Test4Activity.this, "已经第一个了....",
					 0).show();
//					startActivity(new Intent(TestActivity.this,
//							EndTestActivity.class));
//					finish();
					 
					
					}

				break;
			default:
				break;
			}
		}
	};
	private TextView tv_test4_example;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_test4);

		chapterid = DataStoreUtil.getLong(Test4Activity.this, "CHOOSRCHAPTER");
		initview();

		tv_title.setText("Task4");
		
		
		SQLdm s = new SQLdm();
		db = s.openDatabase(Test4Activity.this);
		// 根据获得的章节数获取taskid
//		taskidcur = db.rawQuery("", null);

		tasklist = new ArrayList<Long>();
		Log.e("chapterid------", chapterid + "");
		// 查询小关中的task 返回值 是 task集合
		String sql = "select * from unit where pid=?;";
		Cursor cursor = db.rawQuery(sql, new String[] { chapterid.toString() });
		while (cursor.moveToNext()) {
			long taskid = cursor.getLong(cursor.getColumnIndex("id"));
			// Log.e("taskid----", taskid + "");
			tasklist.add(taskid);
		}
		if (cursor != null) {
			// Log.e("TAG", "eeeeee");
			cursor.close();
			cursor = null;
		}

		wordexampinfos = new ArrayList<WordExampInfo>();
		exampInfocur = db.rawQuery(
				"select * from word where pid=" + tasklist.get(3) + ";", null);
		while (exampInfocur.moveToNext()) {
			WordExampInfo examinfo = new WordExampInfo();
			examinfo.wordid = exampInfocur.getLong(exampInfocur
					.getColumnIndex("id"));
			examinfo.bold = exampInfocur.getString(exampInfocur
					.getColumnIndex("bold"));
			examinfo.word_example = exampInfocur.getString(exampInfocur
					.getColumnIndex("word_example"));
			examinfo.word_translation = exampInfocur.getString(exampInfocur
					.getColumnIndex("word_translation"));
			examinfo.answer_one = exampInfocur.getString(exampInfocur
					.getColumnIndex("answer_one"));
			examinfo.answer_two = exampInfocur.getString(exampInfocur
					.getColumnIndex("answer_two"));
			examinfo.answer_three = exampInfocur.getString(exampInfocur
					.getColumnIndex("answer_three"));
			examinfo.word_ex_tra = exampInfocur.getString(exampInfocur
					.getColumnIndex("word_example_translation"));
			wordexampinfos.add(examinfo);
			Log.e("WORDEXAMPINFOS", examinfo.word_example.toString());
		}
		if(exampInfocur!=null){
			exampInfocur.close();
		}

		studyWord(wordexampinfos);

		pb_test4.setProgress(1);
		pb_test4.setMax(wordexampinfos.size());
		
	}

	private void studyWord(List<WordExampInfo> wordexampinfos) {
		// TODO Auto-generated method stub
		restoreColor();
		//修改单词颜色
		String word = wordexampinfos.get(i).bold;
		int fstart=wordexampinfos.get(i).word_example.indexOf(word.trim());
		Log.e("TAG---fstart---", fstart+"");
		Log.e("TAG---word_example---", wordexampinfos.get(i).word_example+"");
		if(fstart<0){
			fstart=0;
		}
		int fend=fstart+word.trim().length();
		Log.e("TAG---word---", word);
		
		Log.e("TAG---fend---", fend+"");
		SpannableStringBuilder style=new SpannableStringBuilder(wordexampinfos.get(i).word_example); 
		style.setSpan(new ForegroundColorSpan(Color.RED),fstart,fend,Spannable.SPAN_EXCLUSIVE_INCLUSIVE); 
		
		tv_test4_exp.setText(style);
		// List<String> answerList =
		// CXRadom.getWrongAn(wordexampinfos.get(i).wtrans);
		String answer = null;

		int position = new Random().nextInt(4);
		int ps = Math.abs(position);
		Log.e("TAG----ps", ps+"");
		// answer = answerList.get(position);
		switch (ps) {
		case 0:
			Log.e("TAG----1--", ps+"");
			tv_test4_c1.setText(wordexampinfos.get(i).word_translation);
			tv_test4_c2.setText(wordexampinfos.get(i).answer_one);
			tv_test4_c3.setText(wordexampinfos.get(i).answer_two);
			tv_test4_c4.setText(wordexampinfos.get(i).answer_three);
			break;
		case 1:
			Log.e("TAG----2--", ps+"");
			tv_test4_c1.setText(wordexampinfos.get(i).answer_one);
			tv_test4_c2.setText(wordexampinfos.get(i).word_translation);
			tv_test4_c3.setText(wordexampinfos.get(i).answer_two);
			tv_test4_c4.setText(wordexampinfos.get(i).answer_three);
			break;
		case 2:
			Log.e("TAG----3--", ps+"");
			tv_test4_c1.setText(wordexampinfos.get(i).answer_one);
			tv_test4_c2.setText(wordexampinfos.get(i).answer_two);
			tv_test4_c3.setText(wordexampinfos.get(i).word_translation);
			tv_test4_c4.setText(wordexampinfos.get(i).answer_three);
			break;
		default:
			Log.e("TAG----4--", ps+"");
			tv_test4_c1.setText(wordexampinfos.get(i).answer_one);
			tv_test4_c2.setText(wordexampinfos.get(i).answer_two);
			tv_test4_c3.setText(wordexampinfos.get(i).answer_three);
			tv_test4_c4.setText(wordexampinfos.get(i).word_translation);
			break;
		}

		addListener();
	}

	private void addListener() {
		// TODO Auto-generated method stub
		tv_test4_c1.setOnClickListener(this);
		tv_test4_c2.setOnClickListener(this);
		tv_test4_c3.setOnClickListener(this);
		tv_test4_c4.setOnClickListener(this);
		iv_back_tomain.setOnClickListener(this);
		iv_test4_save.setOnClickListener(this);
		iv_test4_lastone.setOnClickListener(this);
		rl_test4.setOnClickListener(this);
	}

	/**
	 * 回复原本颜色
	 */
	private void restoreColor() {
		// TODO Auto-generated method stub
		iv_test4_save.setBackgroundResource(R.drawable.icon_save);
		tv_test4_c1.setBackgroundResource(R.drawable.text_color);
		tv_test4_c2.setBackgroundResource(R.drawable.text_color);
		tv_test4_c3.setBackgroundResource(R.drawable.text_color);
		tv_test4_c4.setBackgroundResource(R.drawable.text_color);
	}

	private void initview() {
		iv_live = (ImageView) findViewById(R.id.iv_live);
		iv_playagain = (ImageView) findViewById(R.id.iv_playagain);
		iv_playnext = (ImageView) findViewById(R.id.iv_playnext);
		iv_starcount = (ImageView) findViewById(R.id.iv_starcount);
		tv_rightlv = (TextView) findViewById(R.id.tv_rightlv);
		rl_end = (RelativeLayout) findViewById(R.id.rl_end);
		iv_playagain_die = (ImageView) findViewById(R.id.iv_playagain_die);

		tv_test4_exp = (TextView) findViewById(R.id.tv_test4_exp);
		tv_test4_c1 = (TextView) findViewById(R.id.tv_test4_c1);
		tv_test4_c2 = (TextView) findViewById(R.id.tv_test4_c2);
		tv_test4_c3 = (TextView) findViewById(R.id.tv_test4_c3);
		tv_test4_c4 = (TextView) findViewById(R.id.tv_test4_c4);
		iv_test4_lastone = (ImageView) findViewById(R.id.iv_test4_lastone);
		iv_test4_save = (ImageView) findViewById(R.id.iv_test4_save);
		pb_test4 = (ProgressBar) findViewById(R.id.pb_test4);
		
		tv_test4_translation = (TextView) findViewById(R.id.tv_test4_translation);
		tv_test4_example = (TextView) findViewById(R.id.tv_test4_example);
		rl_test4 = (RelativeLayout) findViewById(R.id.rl_test4);
		
		tv_title = (TextView) findViewById(R.id.tv_title);
		iv_back_tomain = (LinearLayout) findViewById(R.id.iv_back_tomain);
	}

	private void setOnListener() {
		iv_playagain.setOnClickListener(this);
		iv_playnext.setOnClickListener(this);
		iv_playagain_die.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_playagain:
			startActivity(new Intent(Test4Activity.this, TaskActivity.class));
			finish();
			break;
		case R.id.iv_playnext:
			startActivity(new Intent(Test4Activity.this, MainActivity.class));
			finish();
			break;
		case R.id.iv_playagain_die:
			startActivity(new Intent(Test4Activity.this, TaskActivity.class));
			finish();
			break;
		case R.id.tv_test4_c1:
			judgeAnswer(tv_test4_c1);

			break;
		case R.id.tv_test4_c2:
			judgeAnswer(tv_test4_c2);
			break;
		case R.id.tv_test4_c3:
			judgeAnswer(tv_test4_c3);

			break;
		case R.id.tv_test4_c4:
			judgeAnswer(tv_test4_c4);
			break;
		case R.id.iv_back_tomain:
			startActivity(new Intent(Test4Activity.this, TaskActivity.class));
			finish();
			break;
		case R.id.iv_test4_save:
			// 收藏单词
//			saveWord();
			iv_test4_save.setBackgroundResource(R.drawable.icon_save1);
			break;
		case R.id.iv_test4_lastone:
			 handler.sendEmptyMessage(LASTWHAT);
			break;
		case R.id.rl_test4:
			rl_test4.setVisibility(8);
			handler.sendEmptyMessageDelayed(WHAT, 200);
			break;
		default:
			break;
		}

	}

	/**
	 * 对选择的汉语答案进行判断
	 */
	private void judgeAnswer(TextView textview) {

		long user_id = DataStoreUtil.getLong(Test4Activity.this, "userid");
		long role_id = DataStoreUtil.getLong(Test4Activity.this, "roleid");
		long wordid = wordexampinfos.get(i).wordid;

		/**
		 * 对当前看到的单词数进行记录
		 */
		// 记录单词进度
		if (role_id == 1) {
			ContentValues v = new ContentValues();
			v.put("word_id", wordexampinfos.get(i).wordid);
			db.update("role1", v, "user_id=" + user_id + "", null);

			// if(word_progress.)
		} else if (role_id == 2) {
			Log.e("jinbujin", "jinbujin");
			ContentValues v = new ContentValues();
			v.put("word_id", wordexampinfos.get(i).wordid);

			db.update("role2", v, "user_id=" + user_id + "", null);

		} else {
			ContentValues v = new ContentValues();
			v.put("word_id", wordexampinfos.get(i).wordid);
			db.update("role3", v, "user_id=" + user_id + "", null);
		}

		textview.setBackgroundResource(R.drawable.text_color);
		String uersan = textview.getText().toString();
		
		//回答正确
		if (uersan.equals(wordexampinfos.get(i).word_translation)) {

			ContentValues values = new ContentValues();
			values.put("word_right", 2);// key为字段名，value为值
			db.update("word", values, "id=?",
					new String[] { wordexampinfos.get(i).wordid + "" });

			textview.setBackgroundColor(Color.GREEN);
			// Message msg = new Message();
			Toast.makeText(Test4Activity.this, "回答正确....", 0).show();
			handler.sendEmptyMessageDelayed(WHAT, 500);
		}else{
			textview.setBackgroundColor(Color.RED);
			tv_test4_translation.setText(wordexampinfos.get(i).word_translation);
			tv_test4_example.setText(wordexampinfos.get(i).word_ex_tra);
			setNoClick();
			rl_test4.setVisibility(0);
		}
	}

	private void setNoClick() {
		// TODO Auto-generated method stub
		tv_test4_c1.setClickable(false);
		tv_test4_c2.setClickable(false);
		tv_test4_c3.setClickable(false);
		tv_test4_c4.setClickable(false);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if(db!=null){
			db.close();
		}
	}
}
